package hxg.com;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @author HeXiangGuang
 * @create 2021-03-31 22:52
 */
public class CallableTest {
    public static void main(String[] args) {
        //callable 是一个有放回值的接口类
        Callable<Integer> callable = new Callable<Integer>(){

            @Override
            public Integer call() throws Exception {
                System.out.println(Thread.currentThread().getName()+"开始计算");
                int sum = 0;
                for (int i = 0; i < 100; i++) {
                    //添加休眠
                    Thread.sleep(10);
                    sum+=i;
                }
                return sum;
            }
        };
        //2。要把Callable对象转换成可以执行的任务
        FutureTask<Integer> task = new FutureTask<Integer>(callable);
        //3.创建线程
        Thread thread = new Thread(task);
        //4.启动线程
        thread.start();
        //5.获取结果（因为callable是一个带有放回值的接口类）(这个结果会等待call方法执行完毕,才会返回)
        Integer sum = null;
        try {
            sum = task.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println(sum);
    }
}
